import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.*;

public class GUI{

    JLabel Pic; //图片，用于拖动
    JFrame frame;
    JPanel panel;

    public GUI()
    {
//        JFrame frame=new JFrame();
//        frame.setTitle("HelloWorldApp");
//        frame.setSize(500, 300);
//        JLabel label=new JLabel("Hello World");new ImageIcon("src/rescource/images/4.jpeg")
//        JPanel panel=new JPanel();
//        panel.add(label);
//        frame.setContentPane(panel);
//        frame.setVisible(true);
        frame=new JFrame("Hello World的拖动");
        Pic = new JLabel("Hello World");
        panel=new JPanel();
        panel.setBackground(Color.white);
        panel.add(Pic);

        //事件
        MyMouseInputAdapter listener=new MyMouseInputAdapter();  //鼠标事件处理
        Pic.addMouseListener(listener);  //增加标签的鼠标事件处理
        Pic.addMouseMotionListener(listener);

        frame.add(panel);
        frame.setSize(400,300);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    class MyMouseInputAdapter extends MouseInputAdapter{
        Point point=new Point(0,0); //坐标点

        public void mousePressed(MouseEvent e)
        {
            point=SwingUtilities.convertPoint(Pic,e.getPoint(),Pic.getParent()); //得到当前坐标点
        }

        public void mouseDragged(MouseEvent e)
        {
            Point newPoint=SwingUtilities.convertPoint(Pic,e.getPoint(),Pic.getParent()); //转换坐标系统
            Pic.setLocation(Pic.getX()+(newPoint.x-point.x),Pic.getY()+(newPoint.y-point.y)); //设置标签图片的新位置
            point=newPoint; //更改坐标点
        }
    }

    public static void main(String[] args){
        new GUI();
    }
}